package org.deltaset.samples.petclinic.visit;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.ManagedBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.deltaset.meta.annotation.DsDefaultFinder;
import org.deltaset.meta.annotation.DsFirstResult;
import org.deltaset.meta.annotation.DsMaxResult;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author dmakariev
 */
@ManagedBean
public class AnimalRepositoryImpl extends AbstractAnimalRepository {

    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    protected EntityManager getEntityManager() {
        return entityManager;
    }

    @Transactional
    @Override
    public void delete(Animal animal) {
        final Object forDelete = getEntityManager().getReference(Animal.class, animal.getId());
        getEntityManager().remove(forDelete);
    }

    @Transactional
    @Override
    public void save(Animal entity) {
        getEntityManager().merge(entity);
    }

    @Override
    public Animal findById(String id) {
        final Animal entity = getEntityManager().find(Animal.class, id);
        if (null == entity) {
            throw new IllegalArgumentException("Animal with id=" + id + " not found");
        }
        return entity;
    }

    @Override
    public Long countAll() {
        return getEntityManager().createQuery("SELECT count(*) from " + Animal.class.getName() + " o", Long.class).
                getSingleResult();
    }

    @Transactional
    @DsDefaultFinder
    @Override
    public List<Animal> findAll(@DsFirstResult Integer firstResult, @DsMaxResult Integer maxResult) {
        final List<Animal> founded = getEntityManager().createQuery("FROM " + Animal.class.getName() + " o ORDER BY o.name").
                setFirstResult(firstResult).
                setMaxResults(maxResult).getResultList();
        return new ArrayList<Animal>(founded);
    }

    @Override
    public Animal edit(Animal entity) {
        return entity;
    }

    @Override
    public boolean disableEdit(Animal entity) {
        return null == entity.getId();
    }

    @Override
    public boolean disableDelete(Animal entity) {
        return null == entity.getId();
    }
}
